package com.cheng.im.gateway.processer;

import com.cheng.im.common.constants.ProtoInstants;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.cheng.im.gateway.mq.RocketMQProduce;
import com.cheng.im.gateway.protobuilder.ChatMsgBuilder;
import com.cheng.im.gateway.protobuilder.ChatResponseBuilder;
import com.cheng.im.gateway.session.LocalSession;
import com.cheng.im.gateway.session.ServerSession;
import com.cheng.im.gateway.session.manager.SessionManger;
import com.cheng.im.service.common.resp.CommonResult;
import com.cheng.im.service.message.service.CheckSendMessageService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Data
@Slf4j
@Service("ChatRedirectProcessor")
public class ChatRedirectProcessor {

    @DubboReference
    private CheckSendMessageService checkSendMessageService;
    @Resource
    ChatResponseBuilder chatResponseBuilder;
    @Resource
    ChatMsgBuilder chatMsgBuilder;
    @Resource
    RocketMQProduce rocketMQProduce;

    // todo: 发送成功得有ack
    public Boolean action(LocalSession fromSession, ProtoMsgV1.Message proto) {
        // 聊天处理
        ProtoMsgV1.MessageRequest messageRequest = proto.getMessageRequest();
        // 获取接收方的chatID
        String to = messageRequest.getTo();
        // int platform = messageRequest.getPlatform();

        // 检验是否可以发送 todo: appid还没加到客户端，这边暂时使用固定值
        CommonResult checkResult = checkSendMessageService
                .checkFriendShip(messageRequest.getFrom(), messageRequest.getTo(), "HMYY");
        if(!checkResult.isOk()){
            ProtoMsgV1.Message message = chatResponseBuilder
                    .chatResponse(proto.getSequence(), ProtoInstants.ResultCodeEnum.NOT_ALLOW_SEND);
            // 非好友关系不能发送
            fromSession.getChannel().writeAndFlush(message);
            return false;
        }
        // todo：消息发送到MQ队列落盘
//        rocketMQProduce.sendMessage(proto);

        // todo: 同步消息给其他端
        String from = messageRequest.getFrom();
        List<ServerSession> fromSessions = SessionManger.inst()
                .getSessionsByExclusiveCurrent(from, fromSession, proto.getAppId());
        if (fromSessions == null) {
            // 接收方离线
        } else {
            fromSessions.forEach((session) ->
            {
                ProtoMsgV1.Message message = chatMsgBuilder.chatMsg(proto, session.getSessionId());
                session.writeAndFlush(message);
            });
        }

        if (messageRequest.getFrom().equals(to)) {
            return true;
        }

        // todo: 发送给接收端
        List<ServerSession> toSessions = SessionManger.inst().getSessionsBy(to, proto.getAppId());

        if (toSessions == null) {
            // 接收方离线
        } else {
            toSessions.forEach((session) ->
            {
                log.info("开发转发消息");
                // 将IM消息发送到接收客户端；
                // 如果是remoteSession，则转发到对应的服务节点
                ProtoMsgV1.Message message = chatMsgBuilder.chatMsg(proto, session.getSessionId());
                session.writeAndFlush(message);
            });
        }
        return null;
    }
}
